package com.test.memoryapp;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SSHFileReader {
	public String filePath;
	public String fileNm;
	public String delimeter;
	public List<String> colNmList;

	public SSHFileReader(String _filePath, String _fileNm, String _delimeter,
			String[] _colNmList) {
		super();
		this.filePath = new String(_filePath);
		this.fileNm = new String(_fileNm);
		this.delimeter = new String(_delimeter);
		this.colNmList = new ArrayList<String>();
		for (String colNm : _colNmList) {
			colNmList.add(colNm);
		}
	}
	
	public String getEncodeType(String filePath, String fileNm) throws IOException{
		String encodeType = "UTF-8";
		
		FileInputStream fis;		
		fis = new FileInputStream(filePath + fileNm);
		byte[] BOM = new byte[4];
		fis.read(BOM, 0, 4);
		 
		if( (BOM[0] & 0xFF) == 0xEF && (BOM[1] & 0xFF) == 0xBB && (BOM[2] & 0xFF) == 0xBF )
			encodeType = "UTF-8";
		else if( (BOM[0] & 0xFF) == 0xFE && (BOM[1] & 0xFF) == 0xFF )
			encodeType = "UTF-16BE";
		else if( (BOM[0] & 0xFF) == 0xFE && (BOM[1] & 0xFF) == 0xFE )
			encodeType = "UTF-16LE";
		else if( (BOM[0] & 0xFF) == 0x00 && (BOM[1] & 0xFF) == 0x00 &&
		      (BOM[0] & 0xFF) == 0xFE && (BOM[1] & 0xFF) == 0xFF)
			encodeType = "UTF-32BE";
		else if( (BOM[0] & 0xFF) == 0xFF && (BOM[1] & 0xFF) == 0xFE &&
		      (BOM[0] & 0xFF) == 0x00 && (BOM[1] & 0xFF) == 0x00)
			encodeType = "UTF-32LE";
		else
			encodeType = "EUC-KR";
		
		return encodeType;
	}

	public List<Map<String, String>> getList() throws IOException {
		try {
			String encodeType = getEncodeType(filePath, fileNm);
			BufferedReader buffer = new BufferedReader(new InputStreamReader(new FileInputStream(filePath+fileNm),encodeType));			
			
			String strReadLine;

			List<Map<String, String>> rows = new ArrayList<Map<String, String>>();

			while ((strReadLine = buffer.readLine()) != null) {
				if (strReadLine.substring(0, 1).equals("#")) continue;
				String[] arrColValues = strReadLine.split(delimeter);
				Map<String, String> row = new HashMap<String, String>();
				for (int i = 0; i < arrColValues.length; i++) {
					String strColNm = (colNmList.size() > i) ? colNmList.get(i)
							: "unKnown";
					row.put(strColNm, arrColValues[i]);
				}

				if (!row.isEmpty())
					rows.add(row);
			}
			buffer.close();
			return rows;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
